﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MyWebApplication.Model;

namespace MyWebApplication.Logic
{
	internal class SimpleStore : IStore
	{
		public List<Person> PersonsList { get; set; } 
		public List<Reward> RewardsList { get; set; }
		public Dictionary<Guid, List<Guid>> PersonRewardsList { get; set; }

		public SimpleStore()
		{
			PersonsList = new List<Person>();
			RewardsList = new List<Reward>();
			PersonRewardsList = new Dictionary<Guid, List<Guid>>();
		}

		public bool AddPerson(Person person)
		{
			person.Id = Guid.NewGuid();
			PersonsList.Add(person);
			return true;
		}

		public bool AddPersonReward(Guid person, Guid reward)
		{
			if (!PersonRewardsList.ContainsKey(person))
				PersonRewardsList.Add(person, new List<Guid>());

			PersonRewardsList.Single(x => x.Key.Equals(person)).Value.Add(reward);

			return true;
		}

		public bool AddReward(Reward reward)
		{
			reward.Id = Guid.NewGuid();
			RewardsList.Add(reward);

			return true;
		}

		public void EditPerson(Person person)
		{
			var x = GetPerson(person.Id);
			x.BirthDate = person.BirthDate;
			x.Name = person.Name;
			x.Image = person.Image;
		}

		public void EditReward(Reward reward)
		{
			var x = GetReward(reward.Id);
			x.Title = reward.Title;
			x.Description = reward.Description;
			x.Image = reward.Image;
		}

		public byte[] GetPersonsList()
		{
			var sb = new StringBuilder();

			foreach (var person in PersonsList)
				sb.AppendFormat("?pId: {0}\n?pName: {1}\n?pBirth: {2}\n?pAge: {3}\n", person.Id, person.Name, person.BirthDate.ToString("D"), person.Age);

			return Encoding.UTF8.GetBytes(sb.ToString());
		}

		public void GetPagePersons()
		{
			throw new NotImplementedException();
		}

		public Reward GetReward(Guid id)
		{
			return RewardsList.SingleOrDefault(x => x.Id == id);
		}

		public Person GetPerson(Guid id)
		{
			return PersonsList.SingleOrDefault(x => x.Id == id);
		}

		public PersonReward GetPersonRewards(Guid personId)
		{
			var person = PersonsList.Single(x => x.Id.Equals(personId));
			var allRewards = RewardsList;

			var personRewardsListIds = new List<Guid>();
			if (PersonRewardsList.ContainsKey(personId))
				personRewardsListIds = PersonRewardsList.Single(x => x.Key.Equals(personId)).Value;
			var personRewards = RewardsList.Where(x => personRewardsListIds.Contains(x.Id)).ToList();

			return new PersonReward
			{
				AllRewards = allRewards,
				Person = person,
				PersonRewards = personRewards
			};
		}

		public List<Person> GetPersons()
		{
			return PersonsList;
		}

		public List<Reward> GetRewards()
		{
			return RewardsList;
		}
	}
}